﻿package  
{
	import commands.request.IRequestCommands;
	import flash.events.IEventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.XMLSocket;
	import flash.events.SecurityErrorEvent;
	import flash.events.IOErrorEvent;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	/**
	 * ...
	 * @author Rami
	 */
	public class SocketConnector
	{
		private var _xmlSocket:XMLSocket;
		private var _eventsReactor:Reactor;
		private var _eventProactor:Proactor;
		public function SocketConnector(host : String = "127.0.0.1", port : int=9123) 
		{
			this._eventsReactor = new Reactor();
			this._eventProactor = new Proactor(this);
			this._xmlSocket = new XMLSocket(host, port);
			this.configureListeners(this._xmlSocket);
		}
		
		public function sendCommand(command : String):void
		{
			this._xmlSocket.send(command);
		}
		
		public function getProactor():Proactor
		{
			return this._eventProactor;
		}
		
		public function getReactor():Reactor
		{
			return this._eventsReactor;
		}

		
		private function configureListeners(dispatcher:IEventDispatcher):void {
			dispatcher.addEventListener(Event.CLOSE, closeHandler);
            dispatcher.addEventListener(Event.CONNECT, connectHandler);
            dispatcher.addEventListener(DataEvent.DATA, dataHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
        }

        private function closeHandler(event:Event):void {
            trace("closeHandler: " + event);
        }

        private function connectHandler(event:Event):void {
            trace("connectHandler: " + event);
        }

        private function dataHandler(event:DataEvent):void {
            trace("dataHandler: " + event);
			this._eventsReactor.executeCommands(event.data);
			//var loader:URLLoader = new URLLoader(); 
			//loader.addEventListener(Event.COMPLETE, loadXML); 
			//loader.load(new URLRequest("command.xml"));
			
			
        }

		private function loadXML(e:Event):void
		{
              var xml:XML = new XML(e.target.data);
              trace(xml);
		}



        private function ioErrorHandler(event:IOErrorEvent):void {
            trace("ioErrorHandler: " + event);
        }

        private function progressHandler(event:ProgressEvent):void {
            trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void {
            trace("securityErrorHandler: " + event);
        }

		
	}

}